package com.gc.service.impl;

import com.gc.dao.GcAuthCodeDao;
import com.gc.pojo.GcAuthCode;
import com.gc.service.GcAuthCodeService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.Date;

@Service
public class GcAuthCodeServiceImpl implements GcAuthCodeService {


    @Autowired
    private GcAuthCodeDao gcAuthCodeDao;

    @Value("${config.code.validate.expire}")
    private int codeExpireSeconds;

    @Override
    public void createAuthCode(String email, String code) {

        //设置超时时间
        long createTime = System.currentTimeMillis();
        long expireTime = createTime + codeExpireSeconds * 1000*60;

        GcAuthCode gcAuthCode = new GcAuthCode();
        gcAuthCode.setEmail(email);
        gcAuthCode.setCode(code);
        gcAuthCode.setCreatetime(new Date(createTime));
        gcAuthCode.setExpiretime(new Date(expireTime));
        gcAuthCodeDao.save(gcAuthCode);

    }

    @Override
    public int validateAuthCode(String email, String code) {

        GcAuthCode latest = gcAuthCodeDao.findFirstByEmailOrderByIdDesc(email);
        //0-正确，1-错误，2-超时
        if (latest == null){
            return 1;
        }
        if (!latest.getCode().equalsIgnoreCase(code)){
            return 1;
        }

        long expireTime = latest.getExpiretime().getTime();
        if (expireTime <= System.currentTimeMillis()){
            return 2;
        }
        return 0;
    }
}
